from django.shortcuts import render
from rest_framework.filters import OrderingFilter
from rest_framework.generics import CreateAPIView, ListAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response
from django_redis import get_redis_connection

# Create your views here.
from goods.models import SKU
from orders.models import OrderInfo, OrderGoods
from orders.serializers import OrderShowSerializers, SaveOrderSerializer, UserOrderSerializer, GoodsCommentsSerializer, \
    GoodsCommentSerializer
from decimal import Decimal

from orders.utils import OrderInfoPageNum


class OrderShowView(APIView):
    """
        订单商品展示
    """

    def get(self, request):
        # 1、获取当前用户
        user = request.user
        # 2、提取redis中选中状态的sku_id
        conn = get_redis_connection('cart')
        # 获取商品数据量
        sku_count = conn.hgetall('cart_%s' % user.id)  # {'sku_id':'count'}
        sku_ids = conn.smembers('cart_selectes_%s' % user.id)

        order_dict = {}
        for sku_id, count in sku_count.items():
            if sku_id in sku_ids:
                order_dict[int(sku_id)] = int(count)

        # 3、查询选中状态的商品对象
        skus = SKU.objects.filter(id__in=sku_ids)
        for sku in skus:
            sku.count = order_dict[sku.id]

        freight = Decimal(10.00)
        # 4、序列化返回
        ser = OrderShowSerializers({'freight': freight, 'skus': skus})
        return Response(ser.data)


class SaveOrderView(CreateAPIView,ListAPIView):
    """
    保存订单


    """
    permission_classes = [IsAuthenticated]
    serializer_class = SaveOrderSerializer


class UserOrdersView(ListAPIView):
    """
        显示订单
    """
    serializer_class = UserOrderSerializer
    # 分页设置
    pagination_class = OrderInfoPageNum

    filter_backends = [OrderingFilter]
    ordering_fields = ('create_time')

    def get_queryset(self):
        pk = self.request.user.id
        order_info = OrderInfo.objects.filter(user_id=pk).order_by("create_time")
        return order_info




class GoodsCommentsView(ListAPIView,APIView):
    """
        商品单个评论显示
        商品单个评论提交
    """
    serializer_class = GoodsCommentsSerializer

    def get_queryset(self):
        order_id = self.kwargs['order_id']
        order_goods_list = OrderGoods.objects.filter(order_id = order_id,is_commented = False)
        return order_goods_list
    """
        订单中单个商品评价提交
    """
    def post(self, request, order_id):
        data = request.data
        try:
            order_good = OrderGoods.objects.get(order_id=data['order'], sku_id=data['sku'])
        except:
            return Response("订单不商品")
        ser = GoodsCommentSerializer(order_good, data=data)
        ser.is_valid(raise_exception=True)
        ser.save()
        return Response({})






